//
//  sdl_player_2_display.c
//  FFmpegDemo
//
//  Created by xiaerfei on 2019/4/20.
//  Copyright © 2019 erfeixia. All rights reserved.
//

#include "sdl_player_2_display.h"
#include <SDL2/SDL.h>
#include <assert.h>

#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
#include <libswscale/swscale.h>
#include <libswresample/swresample.h>
#include <libavutil/avstring.h>
#include <libavutil/time.h>



#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wsometimes-uninitialized"
#pragma clang diagnostic ignored "-Wdeprecated-declarations"


#define SDL_AUDIO_BUFFER_SIZE 1024

#define MAX_AUDIO_FRAME_SIZE 192000

#define MAX_AUDIOQ_SIZE (5 * 16 * 1024)
#define MAX_VIDEOQ_SIZE (5 * 256 * 1024)

#define FF_REFRESH_EVENT    (SDL_USEREVENT)
#define FF_QUIT_EVENT       (SDL_USEREVENT + 1)

#define VIDEO_PICTURE_QUEUE_SIZE 1

#define AV_SYNC_THRESHOLD 0.01
#define AV_NOSYNC_THRESHOLD 10.0

/*
 音视频存放的队列
 */
typedef struct PacketQueue {
    AVPacketList *first_pkt, *last_pkt;
    int nb_packets;
    int size;
    SDL_mutex *mutex;
    SDL_cond *cond;
} PacketQueue;

typedef struct VideoPicture {
    AVPicture *bmp;
    int width, height; /* source height & width */
    int allocated;
    double pts;
} VideoPicture;


typedef struct VideoState {
    AVFormatContext *pFormatCtx; // 上下文
    int video_stream_index; // 视频流索引
    int audio_stream_index; // 音频流索引
///////////////////// 音频相关 - begin //////////////////////////
    AVStream        *audio_stream; // 音频流
    AVCodecContext  *audio_ctx;   // 音频解码上下文
    PacketQueue     audio_queue;  // 音频队列
    
    uint8_t          audio_buf[(MAX_AUDIO_FRAME_SIZE * 3) / 2]; // 音频解码后数据存放buffer
    unsigned int    audio_buf_size;  // buffer size
    unsigned int    audio_buf_index; // buffer 存放的开始位置
    
    AVFrame         audio_frame; // 解码后的音频包
    AVPacket        audio_pkt;   // 解码前的音频包
    
    uint8_t         *audio_pkt_data;
    int             audio_pkt_size;
    int             audio_hw_buf_size;
    struct SwrContext *audio_swr_ctx;
///////////////////// 音频相关 - end ////////////////////////////
///////////////////// 视频相关 - begin //////////////////////////
    AVStream             *video_stream;
    AVCodecContext      *video_ctx;
    PacketQueue         video_queue;
    struct SwsContext   *video_sws_ctx;
///////////////////// 视频相关 - end ////////////////////////////
    
    VideoPicture    pictq[VIDEO_PICTURE_QUEUE_SIZE];
    int             pictq_size, pictq_rindex, pictq_windex;
    
    double          audio_clock;
    double          video_clock; ///<pts of last decoded frame / predicted pts of next decoded frame
    
    double          frame_timer;
    double          frame_last_pts;
    double          frame_last_delay;

    
    SDL_mutex       *pictq_mutex;
    SDL_cond        *pictq_cond;
    
    SDL_Thread      *parse_tid;
    SDL_Thread      *video_tid;
    char            filename[1024];
    int             quit;
    int             width;
    int             height;
    int             linesize[4];
    SDL_Rect       rect;
} VideoState;

SDL_mutex       *text_mutex;
SDL_Window      *win;
SDL_Renderer    *renderer;
SDL_Texture     *texture;
VideoState      *global_video_state;

#pragma mark - 音视频队列初始化
static void packet_queue_init(PacketQueue *q) {
    memset(q, 0, sizeof(PacketQueue));
    q->mutex = SDL_CreateMutex();
    q->cond = SDL_CreateCond();
}

#pragma mark - 音视频入队
static int packet_queue_put(PacketQueue *q, AVPacket *pkt) {
    
    AVPacketList *pkt1;
    if(av_dup_packet(pkt) < 0) {
        return -1;
    }
    pkt1 = av_malloc(sizeof(AVPacketList));
    if (!pkt1)
        return -1;
    pkt1->pkt = *pkt;
    pkt1->next = NULL;
    
    SDL_LockMutex(q->mutex);
    
    if (!q->last_pkt)
        q->first_pkt = pkt1;
    else
        q->last_pkt->next = pkt1;
    q->last_pkt = pkt1;
    q->nb_packets++;
    q->size += pkt1->pkt.size;
    SDL_CondSignal(q->cond);
    
    SDL_UnlockMutex(q->mutex);
    return 0;
}
#pragma mark - 音视频出队
static int packet_queue_get(PacketQueue *q, AVPacket *pkt, int block) {
    AVPacketList *pkt1;
    int ret;
    
    SDL_LockMutex(q->mutex);
    for(;;) {
        if(global_video_state->quit) {
            ret = -1;
            break;
        }
        
        pkt1 = q->first_pkt;
        if (pkt1) {
            q->first_pkt = pkt1->next;
            if (!q->first_pkt)
                q->last_pkt = NULL;
            q->nb_packets--;
            q->size -= pkt1->pkt.size;
            *pkt = pkt1->pkt;
            av_free(pkt1);
            ret = 1;
            break;
        } else if (!block) {
            ret = 0;
            break;
        } else {
            SDL_CondWait(q->cond, q->mutex);
        }
    }
    SDL_UnlockMutex(q->mutex);
    return ret;
}

static int audio_decode_frame(VideoState *is, uint8_t *audio_buf, int buf_size, double *pts_ptr) {
    int len1, data_size = 0;
    AVPacket *pkt = &is->audio_pkt;
    double pts;
    int n;
    
    for(;;) {
        while(is->audio_pkt_size > 0) {
            int got_frame = 0;
            len1 = avcodec_decode_audio4(is->audio_ctx, &is->audio_frame, &got_frame, pkt);
            if(len1 < 0) {
                /* if error, skip frame */
                is->audio_pkt_size = 0;
                break;
            }
            data_size = 0;
            if(got_frame) {
                data_size = 2 * is->audio_frame.nb_samples * 2;
                assert(data_size <= buf_size);
                swr_convert(is->audio_swr_ctx,
                            &audio_buf,
                            MAX_AUDIO_FRAME_SIZE*3/2,
                            (const uint8_t **)is->audio_frame.data,
                            is->audio_frame.nb_samples);
            }
            is->audio_pkt_data += len1;
            is->audio_pkt_size -= len1;
            if(data_size <= 0) {
                /* No data yet, get more frames */
                continue;
            }
            
            pts = is->audio_clock;
            *pts_ptr = pts;
            n = 2 * is->audio_ctx->channels;
            is->audio_clock += (double)data_size /
            (double)(n * is->audio_ctx->sample_rate);
            /* We have data, return it and come back for more later */
            return data_size;
        }
        if(pkt->data) {av_free_packet(pkt);}
        if(is->quit) { return -1;}
        /* next packet */
        if(packet_queue_get(&is->audio_queue, pkt, 1) < 0) { return -1; }
        is->audio_pkt_data = pkt->data;
        is->audio_pkt_size = pkt->size;
        
        if(pkt->pts != AV_NOPTS_VALUE) {
            is->audio_clock = av_q2d(is->audio_stream->time_base) * pkt->pts;
        }
    }
}


#pragma mark - 定时刷新 callback
static void audio_callback(void *userdata, Uint8 *stream, int len) {
    VideoState *is = (VideoState *)userdata;
    int len1, audio_size;
    double pts;
    
    SDL_memset(stream, 0, len);
    
    while(len > 0) {
        if(is->audio_buf_index >= is->audio_buf_size) {
            audio_size = audio_decode_frame(is, is->audio_buf, sizeof(is->audio_buf), &pts);
            if(audio_size < 0) {
                /* If error, output silence */
                is->audio_buf_size = 1024 * 2 * 2;
                memset(is->audio_buf, 0, is->audio_buf_size);
            } else {
                is->audio_buf_size = audio_size;
            }
            is->audio_buf_index = 0;
        }
        len1 = is->audio_buf_size - is->audio_buf_index;
        fprintf(stderr, "stream addr:%p, audio_buf_index:%d, audio_buf_size:%d, len1:%d, len:%d\n",
                stream,
                is->audio_buf_index,
                is->audio_buf_size,
                len1,
                len);
        if(len1 > len) {len1 = len;}
        SDL_MixAudio(stream,(uint8_t *)is->audio_buf + is->audio_buf_index, len1, SDL_MIX_MAXVOLUME);
        len -= len1;
        stream += len1;
        is->audio_buf_index += len1;
    }
}

static Uint32 sdl_refresh_timer_cb(Uint32 interval, void *opaque) {
    SDL_Event event;
    event.type = FF_REFRESH_EVENT;
    event.user.data1 = opaque;
    SDL_PushEvent(&event);
    return 0; /* 0 means stop timer */
}

#pragma mark - 定时器
static void schedule_refresh(VideoState *is, int delay) {
    SDL_AddTimer(delay, sdl_refresh_timer_cb, is);
}

double get_audio_clock(VideoState *is) {
    double pts = 0;
    int hw_buf_size, bytes_per_sec, n;
    
    pts = is->audio_clock; /* maintained in the audio thread */
    hw_buf_size = is->audio_buf_size - is->audio_buf_index;
    bytes_per_sec = 0;
    n = is->audio_ctx->channels * 2;
    if(is->audio_stream) {
        bytes_per_sec = is->audio_ctx->sample_rate * n;
    }
    if(bytes_per_sec) {
        pts -= (double)hw_buf_size / bytes_per_sec;
    }
    return pts;
}


void alloc_picture(void *userdata) {
    int ret;
    
    VideoState *is = (VideoState *)userdata;
    VideoPicture *vp;
    
    vp = &is->pictq[is->pictq_windex];
    if(vp->bmp) {
        // we already have one make another, bigger/smaller
        avpicture_free(vp->bmp);
        free(vp->bmp);
        vp->bmp = NULL;
    }
    
    // Allocate a place to put our YUV image on that screen
    SDL_LockMutex(text_mutex);
    
    vp->bmp = (AVPicture*)malloc(sizeof(AVPicture));
    ret = avpicture_alloc(vp->bmp, AV_PIX_FMT_YUV420P, is->video_ctx->width, is->video_ctx->height);
    if (ret < 0) {
        fprintf(stderr, "Could not allocate temporary picture: %s\n", av_err2str(ret));
    }
    
    SDL_UnlockMutex(text_mutex);
    
    vp->width = is->video_ctx->width;
    vp->height = is->video_ctx->height;
    vp->allocated = 1;
}


static int queue_picture(VideoState *is, AVFrame *pFrame, double pts) {
    VideoPicture *vp;
    
    /* wait until we have space for a new pic */
    SDL_LockMutex(is->pictq_mutex);
    while(is->pictq_size >= VIDEO_PICTURE_QUEUE_SIZE && !is->quit) {
        SDL_CondWait(is->pictq_cond, is->pictq_mutex);
    }
    SDL_UnlockMutex(is->pictq_mutex);
    
    if(is->quit) return -1;
    
    vp = &is->pictq[is->pictq_windex];
    
    /* allocate or resize the buffer! */
    if(!vp->bmp ||
       vp->width != is->video_ctx->width ||
       vp->height != is->video_ctx->height) {
        vp->allocated = 0;
        alloc_picture(is);
        if(is->quit) {
            return -1;
        }
    }
    /* We have a place to put our picture on the queue */
    if(vp->bmp) {
        vp->pts = pts;
        // Convert the image into YUV format that SDL uses
        sws_scale(is->video_sws_ctx, (uint8_t const * const *)pFrame->data,
                  pFrame->linesize, 0, is->video_ctx->height,
                  vp->bmp->data, is->linesize);
        
        /* now we inform our display thread that we have a pic ready */
        if(++is->pictq_windex == VIDEO_PICTURE_QUEUE_SIZE) {
            is->pictq_windex = 0;
        }
        
        SDL_LockMutex(is->pictq_mutex);
        is->pictq_size++;
        SDL_UnlockMutex(is->pictq_mutex);
    }
    
    return 0;
}

double synchronize_video(VideoState *is, AVFrame *src_frame, double pts) {
    double frame_delay;
    
    if(pts != 0) {
        /* if we have pts, set video clock to it */
        is->video_clock = pts;
    } else {
        /* if we aren't given a pts, set it to the clock */
        // 如果时间出错了，就赋值上一次的时间
        pts = is->video_clock;
    }
    
    /* update the video clock */
    // 每一帧的的间隔
    frame_delay = av_q2d(is->video_ctx->time_base);
    /* if we are repeating a frame, adjust clock accordingly */
    // TODO: 这个重复帧的计算还不清楚
    /**
     * When decoding, this signals how much the picture must be delayed.
     * extra_delay = repeat_pict / (2*fps)
     * int repeat_pict;
     */
    frame_delay += src_frame->repeat_pict * (frame_delay * 0.5);
    is->video_clock += frame_delay;
    return pts;
}

int decode_video_thread(void *arg) {
    VideoState *is = (VideoState *)arg;
    AVPacket pkt1, *packet = &pkt1;
    int frameFinished;
    AVFrame *pFrame;
    double pts;
    
    pFrame = av_frame_alloc();
    
    for (;;) {
        if (packet_queue_get(&is->video_queue, packet, 1) < 0) {
            break;
        }
        pts = 0;
        
        // Decode video frame
        avcodec_decode_video2(is->video_ctx, pFrame, &frameFinished, packet);
        if((pts = av_frame_get_best_effort_timestamp(pFrame)) == AV_NOPTS_VALUE) {
            pts = 0;
        }
        // pts(刻度) * 单位时间 = 当前帧的时间(秒)
        pts *= av_q2d(is->video_stream->time_base);
        if (frameFinished) {
            pts = synchronize_video(is, pFrame, pts);
            if (queue_picture(is, pFrame, pts) < 0) {
                break;
            }
        }
        av_free_packet(packet);
    }
    av_frame_free(&pFrame);
    return 0;
}

int stream_component_open(VideoState *is, int stream_index) {
    AVFormatContext *pFormatCtx = is->pFormatCtx;
    AVCodecContext *codecCtx = NULL;
    AVCodec *codec = NULL;
    SDL_AudioSpec wanted_spec, spec;
    
    if(stream_index < 0 || stream_index >= pFormatCtx->nb_streams) {
        return -1;
    }
    
    codecCtx = avcodec_alloc_context3(NULL);
    
    if (avcodec_parameters_to_context(codecCtx, pFormatCtx->streams[stream_index]->codecpar) < 0) {
        return -1;
    }
    codec = avcodec_find_decoder(codecCtx->codec_id);
    if (!codec) {
        fprintf(stderr, "Unsupported codec!\n");
        return -1;
    }
    // 音频
    if (codecCtx->codec_type == AVMEDIA_TYPE_AUDIO) {
        // Set audio settings from codec info
        wanted_spec.freq = codecCtx->sample_rate;
        wanted_spec.format = AUDIO_S16SYS;
        wanted_spec.channels = 2;//codecCtx->channels;
        wanted_spec.silence = 0;
        wanted_spec.samples = SDL_AUDIO_BUFFER_SIZE;
        wanted_spec.callback = audio_callback;
        wanted_spec.userdata = is;
        
        if(SDL_OpenAudio(&wanted_spec, &spec) < 0) {
            fprintf(stderr, "SDL_OpenAudio: %s\n", SDL_GetError());
            return -1;
        }
        is->audio_hw_buf_size = spec.size;
    }
    
    if(avcodec_open2(codecCtx, codec, NULL) < 0) {
        fprintf(stderr, "Unsupported codec!\n");
        return -1;
    }
    
    switch (codecCtx->codec_type) {
        case AVMEDIA_TYPE_AUDIO:
        {
            is->audio_stream_index = stream_index;
            is->audio_stream = pFormatCtx->streams[stream_index];
            is->audio_ctx = codecCtx;
            is->audio_buf_size = 0;
            is->audio_buf_index = 0;
            memset(&is->audio_pkt, 0, sizeof(is->audio_pkt));
            packet_queue_init(&is->audio_queue);

            // TODO: 没看懂啥意思 ❓❓❓
            //Out Audio Param
            uint64_t out_channel_layout = AV_CH_LAYOUT_STEREO;
            int out_sample_rate=is->audio_ctx->sample_rate;

            int64_t in_channel_layout=av_get_default_channel_layout(is->audio_ctx->channels);
            
            struct SwrContext *audio_convert_ctx;
            audio_convert_ctx = swr_alloc();
            swr_alloc_set_opts(audio_convert_ctx,
                               out_channel_layout,
                               AV_SAMPLE_FMT_S16,
                               out_sample_rate,
                               in_channel_layout,
                               is->audio_ctx->sample_fmt,
                               is->audio_ctx->sample_rate,
                               0,
                               NULL);
            fprintf(stderr, "swr opts: out_channel_layout:%lld, out_sample_fmt:%d, out_sample_rate:%d, in_channel_layout:%lld, in_sample_fmt:%d, in_sample_rate:%d\n",
                    out_channel_layout, AV_SAMPLE_FMT_S16, out_sample_rate, in_channel_layout, is->audio_ctx->sample_fmt, is->audio_ctx->sample_rate);
            swr_init(audio_convert_ctx);
            
            is->audio_swr_ctx = audio_convert_ctx;
            
            SDL_PauseAudio(0);
            break;
        }
        case AVMEDIA_TYPE_VIDEO:
        {
            is->video_stream = pFormatCtx->streams[is->video_stream_index];
            is->video_ctx = codecCtx;
            is->frame_timer = (double)av_gettime() / 1000000.0;
            is->frame_last_delay = 40e-3;
            packet_queue_init(&is->video_queue);
            is->linesize[0] = is->video_ctx->width;
            is->linesize[1] = is->video_ctx->width/2;
            is->linesize[2] = is->video_ctx->width/2;
            is->video_sws_ctx = sws_getContext(is->video_ctx->width, is->video_ctx->height,
                                               is->video_ctx->pix_fmt, is->video_ctx->width,
                                               is->video_ctx->height, AV_PIX_FMT_YUV420P,
                                               SWS_BILINEAR, NULL, NULL, NULL
                                               );
            is->video_tid = SDL_CreateThread(decode_video_thread, "decode_video_thread", is);
            break;
        }
            
        default:
            break;
    }
    return 0;
}


#pragma mark - 解复用线程
int demux_thread(void *arg) {
    AVPacket pkt1, *packet = &pkt1;
    
    VideoState *video_state = arg;

    
    for (;;) {
        // 如果退出则发送信号量
        if(video_state->quit) {
            SDL_CondSignal(video_state->video_queue.cond);
            SDL_CondSignal(video_state->audio_queue.cond);
            break;
        }
        // seek stuff goes here
        // TODO: 暂时还不知道什么意思❓❓❓
        if(
           video_state->video_queue.size > MAX_VIDEOQ_SIZE) {
            SDL_Delay(10);
            continue;
        }
        if(av_read_frame(video_state->pFormatCtx, packet) < 0) {
            // < 0 on error or end of file
            if(video_state->pFormatCtx->pb->error == 0) {
                SDL_Delay(100); /* no error; wait for user input */
                continue;
            } else {
                break;
            }
        }
        if (packet->stream_index == video_state->video_stream_index) {
            packet_queue_put(&video_state->video_queue, packet);
        } else if (packet->stream_index == video_state->audio_stream_index) {
            packet_queue_put(&video_state->audio_queue, packet);
        } else {
            av_free_packet(packet);
        }
    }
    
    while (!video_state->quit) {
        SDL_Delay(100);
    }
    
__fail:
    if (1) {
        SDL_Event event;
        event.type = FF_QUIT_EVENT;
        event.user.data1 = video_state;
        SDL_PushEvent(&event);
    }
    return 0;
}

void video_display(VideoState *video_state) {
    VideoPicture *vp = &video_state->pictq[video_state->pictq_rindex];
    
    if (vp->bmp) {
        SDL_UpdateYUVTexture( texture, NULL,
                             vp->bmp->data[0], video_state->linesize[0],
                             vp->bmp->data[1], video_state->linesize[1],
                             vp->bmp->data[2], video_state->linesize[2]);
        SDL_LockMutex(text_mutex);
        SDL_RenderClear( renderer );
        SDL_RenderCopy( renderer, texture, NULL, &video_state->rect);
        SDL_RenderPresent( renderer );
        SDL_UnlockMutex(text_mutex);
    }
}

void video_refresh_timer(void *userdata) {
    VideoState      *video_state = (VideoState *)userdata;
    VideoPicture    *vp;
    double actual_delay, delay, sync_threshold, ref_clock, diff;
    if (video_state->video_stream) {
        if (video_state->pictq_size == 0) {
            // 没有数据 1ms 间隔刷新
            schedule_refresh(video_state, 1);
        } else {
            vp = &video_state->pictq[video_state->pictq_rindex];
            // 当前的pts - 上次的pts
            delay = vp->pts - video_state->frame_last_pts; /* the pts from last time */
            if(delay <= 0 || delay >= 1.0) {
                // <= 0 或者 d >= 1秒 说明有了异常, 采用上次的 delay
                /* if incorrect delay, use previous one */
                delay = video_state->frame_last_delay;
            }
            /* save for next time */
            video_state->frame_last_delay = delay;
            video_state->frame_last_pts = vp->pts;
            
            /* update delay to sync to audio */
            // 计算音频和视频的时间差值
            ref_clock = get_audio_clock(video_state);
            diff = vp->pts - ref_clock;
            // AV_SYNC_THRESHOLD 为阀值 10ms(音频的每个包是 10ms)
            sync_threshold = (delay > AV_SYNC_THRESHOLD) ? delay : AV_SYNC_THRESHOLD;
            // diff > 10s 放弃处理？
            if(fabs(diff) < AV_NOSYNC_THRESHOLD) {
                if(diff <= -sync_threshold) {
                    // 赶不上音频了，要加速了
                    delay = 0;
                } else if(diff >= sync_threshold) {
                    // 超前音频了，开始减速
                    delay = 2 * delay;
                }
            }
            
            video_state->frame_timer += delay;
            actual_delay = video_state->frame_timer - (av_gettime() / 1000000.0);
            if(actual_delay < 0.010) {
                /* Really it should skip the picture instead */
                actual_delay = 0.010;
            }
            schedule_refresh(video_state, (int)(actual_delay * 1000 + 0.5));
            /* show the picture! */
            video_display(video_state);
            /* update queue for next picture! */
            if(++video_state->pictq_rindex == VIDEO_PICTURE_QUEUE_SIZE) {
                video_state->pictq_rindex = 0;
            }
            SDL_LockMutex(video_state->pictq_mutex);
            video_state->pictq_size--;
            SDL_CondSignal(video_state->pictq_cond);
            SDL_UnlockMutex(video_state->pictq_mutex);
        }
    } else {
        schedule_refresh(video_state, 100);
    }
}

static int open_file(VideoState  *video_state) {
    video_state->audio_stream_index = -1;
    video_state->video_stream_index = -1;
    // Open video file
    if(avformat_open_input(&video_state->pFormatCtx, video_state->filename, NULL, NULL) != 0) {
        return -1; // Couldn't open file
    }
    if (avformat_find_stream_info(video_state->pFormatCtx, NULL) < 0) {
        return -1;
    }
    
    av_dump_format(video_state->pFormatCtx, 0, video_state->filename, 0);
    
    for (int i = 0; i < video_state->pFormatCtx->nb_streams; i++) {
        if (video_state->pFormatCtx->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
            video_state->video_stream_index = i;
        }
        if (video_state->pFormatCtx->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
            video_state->audio_stream_index = i;
        }
    }
    
    if (video_state->video_stream_index >= 0) {
        stream_component_open(video_state, video_state->video_stream_index);
    }
    if (video_state->audio_stream_index >= 0) {
        stream_component_open(video_state, video_state->audio_stream_index);
    }
    
    if(video_state->video_stream_index < 0 || video_state->audio_stream_index < 0) {
        fprintf(stderr, "%s: could not open codecs\n", video_state->filename);
        return -1;
    }
    
    return 0;
}


void sdl_player_2_display(void) {
    int ret = -1;
    SDL_Event   event;
    VideoState  *video_state = av_mallocz(sizeof(VideoState));
    video_state->width = 704;
    video_state->height = 528;
    video_state->linesize[0] = 0;
    video_state->linesize[1] = 0;
    video_state->linesize[2] = 0;
    video_state->linesize[3] = 0;
    global_video_state = video_state;
//    const char *file_name = "/Users/xiaerfei/Documents/ffmpegDemo/res/cctv6live1.ts";
//    const char *file_name = "/Users/xiaerfei/Desktop/video/笑傲江湖曲原版高清（原画）.f4v";
    const char *file_name = "/Users/xiaerfei/Downloads/有什么笑话可以笑一辈子.mp4";
//    const char *file_name = "/Users/xiaerfei/Downloads/baiduDownload/流浪地球HD1080P高清国语中字.mp4";
    const char *file_name = "/Users/xiaerfei/Downloads/zhuixu.mp4";
//    const char *file_name = "/Users/xiaerfei/Desktop/video/何必西天万里遥-西游记插曲-高清原画（清晰）.f4v";
    av_strlcpy(video_state->filename, file_name, sizeof(video_state->filename));
    // Register all formats and codecs
    av_register_all();
    
    if (open_file(video_state) == -1) {
        exit(1);
    }
    // SDL 初始化
    if(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_TIMER)) {
        fprintf(stderr, "Could not initialize SDL - %s\n", SDL_GetError());
        exit(1);
    }
    win = SDL_CreateWindow("Media Player",
                           SDL_WINDOWPOS_UNDEFINED,
                           SDL_WINDOWPOS_UNDEFINED,
                           video_state->video_ctx->width,
                           video_state->video_ctx->height,
                           SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE);
    renderer = SDL_CreateRenderer(win, -1, 0);
    texture = SDL_CreateTexture(renderer,
                                SDL_PIXELFORMAT_IYUV,
                                SDL_TEXTUREACCESS_STREAMING,
                                video_state->video_ctx->width,
                                video_state->video_ctx->height);
    video_state->rect.x = 0;
    video_state->rect.y = 0;
    video_state->rect.w = video_state->video_ctx->width;
    video_state->rect.h = video_state->video_ctx->height;
    // 创建锁和信号量
    video_state->pictq_mutex = SDL_CreateMutex();
    video_state->pictq_cond = SDL_CreateCond();
    text_mutex = SDL_CreateMutex();
    // 40ms 刷新 为视频的帧率 如 1/25 每秒 25 帧
    schedule_refresh(video_state, 40);
    // 创建一个解复用线程
    video_state->parse_tid = SDL_CreateThread(demux_thread, "demux_thread", video_state);
    if(!video_state->parse_tid) {
        av_free(video_state);
        goto __FAIL;
    }
    
    for(;;) {
        SDL_WaitEvent(&event);
        switch (event.type) {
            case FF_QUIT_EVENT:
            case SDL_QUIT:
                video_state->quit = 1;
                goto __QUIT;
                break;
            case FF_REFRESH_EVENT:// 视图的刷新
                video_refresh_timer(event.user.data1);
                break;
                
            default:
                break;
        }
    }
    
__QUIT:
    ret = 0;
    
    
__FAIL:
    
    SDL_Quit();
}

#pragma clang diagnostic pop
